var app = getApp();
let innerAudioContext = wx.createInnerAudioContext(); //创建音频实例
const recordmanage = wx.getRecorderManager()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    xturl: app.myUlife.ulifeUrl + "/",
    usid:'',
    navList: [], 
    activeIndex: 0,
    user_type: '1',//1学生 2教师

    works: {
      page: 1,
      limit: 20,
      totalpage: 0,
      datas: []
    },
    totalnum: 0,

    startgray: '../../../images/score_stars_icon_gray.png',//星级灰色
    startyellow: '../../../images/score_stars_icon_yellow.png',//星级黄色

    jfph: {
      page: 1,
      limit: 20,
      totalpage: 0,
      datas: []
    },
    jfph1:[],
    jfph2:[],
    totalydpm: 0,

    readid:'',
    pname: '',
    author: '',
    nj: '',
    bj: '',
    pcontent: '',
    yp: '',
    fm: '',
    scnrimg: [],//诗词内容图片
    yy: [],//诗词语音
    phidden: false,//是否隐藏诗词

    pstatus: false,
    lyimage: app.myUlife.ulifeUrl + '/wx/voice_btn_icon_n.png',//默认图片 

    //诗词录音播放
    formatedPlayTime: '00:00',
    playStatus: true, //未播放的图片
    slider_value: 0,//设置初始滑块位置为0
   
    
    //我的录音
    myformatedPlayTime: '00:00',
    mymusicUrl: '',//音频地址
    myplayStatus: true, //未播放的图片
    myslider_value: 0,//设置初始滑块位置为0

    myyp: '',//我上次的音频

    loading: false,
    plain: false,
    disabled: false,//按钮一旦点击提交 则不能操作

    userpm:0,//当前用户的排名
    userjf:0,//当前用户的积分
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var usid = wx.getStorageSync('usid');
    if (!usid) {
      wx.reLaunch({
        url: '../../../pages/login/login'
      })
      return;
    }
    var user_type = wx.getStorageSync('user_type');
    this.setData({
      readid: options.readid,
      user_type: user_type,
      usid: usid
    })

    if (user_type=="1"){
      this.setData({
        navList: [{
          name: '我的作业',
          _id: '0',
        },
        {
          name: '阅读排名',
          _id: '1',
        }]
      })
    }else{
      this.setData({
        navList: [{
          name: '作业情况',
          _id: '0',
        },
        {
          name: '阅读排名',
          _id: '1',
        }]
      }) 
    }
    //查询诗词详情
    this.getPoetryReadDetail();

    //查询该诗词的完成情况
    this.getAllHomeworkByreadid();
    //查询排名情况
    this.getHomeworkPmByreadid();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  //切换
  onTapTag(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    that.setData({
      activeIndex: index,
    })
  },

  getPoetryReadDetail(){
    var that = this;
    var readid = that.data.readid;
    wx.request({
      url: app.myUlife.ulifeUrl + 'poetryread/getPoetryReadById.html',
      data: {
        readid: readid,
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var datas = res.data;
        that.setData({
          readid: datas.READID,
          pname: datas.PNAME,
          author: datas.AUTHOR,
          nj: datas.NJ,
    
          pcontent: datas.PCONTENT,
          yp: that.data.xturl + datas.YP,
          fm: datas.FM,
        })
        if (datas.scnr){
          that.setData({
            scnrimg: datas.scnr
          })
        }
        if (datas.BJ) {
          that.setData({
            bj: datas.BJ
          })
        }
        if (datas.yy) {
          that.setData({
            yy: datas.yy
          })
        }

        wx.setNavigationBarTitle({
          title: "《" + datas.PNAME + "》"
        })
      }
    })
  },

  getAllHomeworkByreadid: function (e) {
    var that = this;
    var readid = that.data.readid;
    var user_type = wx.getStorageSync('user_type');
    //1学生 2教师
    var usid="";
    if (user_type == "1") {
      usid = wx.getStorageSync('usid');
    }


    var page = that.data.works.page;
    var limit = that.data.works.limit;
    var totalpage = that.data.works.totalpage;
    if (page != 1) {
      if (page > totalpage) {
        return;
      }
    } 

    wx.request({
      url: app.myUlife.ulifeUrl + 'poetryread/getAllHomeworkByreadid.html',
      data: {
        usid: usid,
        readid: readid,
        page: page,
        limit: limit,
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {

        var datas = res.data.list;
        var totalpage = res.data.totalpage;
        var odatas = that.data.works.datas;
        for (var i = 0; i < datas.length; i++) {
          datas[i].myformatedPlayTime="00:00";
          datas[i].myplayStatus=true;
          datas[i].myslider_value="0";
          odatas.push(datas[i]);
        }
        var works = that.data.works;
        works.datas = odatas;
        works.totalpage = totalpage;
        that.setData({
          works: works,
          totalnum: res.data.totalnum,
        })

      }
    })
  },




  //获取阅读排行
  getHomeworkPmByreadid() {
    var that = this;
    var page = that.data.jfph.page;
    var limit = that.data.jfph.limit;
    var totalpage = that.data.jfph.totalpage;
    if (page != 1) {
      if (page > totalpage) {
        return;
      }
    } 
    var readid = that.data.readid;
    var user_type = wx.getStorageSync('user_type');
    //1学生 2教师
    var usid = "";
    if (user_type == "1") {
      usid = wx.getStorageSync('usid');
    }
    wx.request({
      url: app.myUlife.ulifeUrl + 'poetryread/getHomeworkPmByreadid.html',
      data: {
        readid: readid,
        usid: usid,
        page: page,
        limit: limit,
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        //积分排名
        var jfph = that.data.jfph;
        var datas = jfph.datas;

        var jfp = res.data.list;
        var totalpage = res.data.totalpage;
        
        //前三名
        var jfph1 = that.data.jfph1;
        //除去前三名的
        var jfph2 = that.data.jfph2;

        for (var i = 0; i < jfp.length; i++) {
          datas.push(jfp[i]);
        }

        for (var j = 0; j < datas.length; j++) {
          var pm = parseInt(datas[j].PM);
          if (pm <= 3) {
            jfph1.push(datas[j]);
          } else {
            jfph2.push(datas[j]);
          }
          if (datas[j].USID == that.data.usid){
            that.setData({
              userpm: j+1,//当前用户的排名
              userjf: datas[j].PSTATR,//当前用户的积分
            })
          }
        }

        that.setData({
          jfph1: jfph1,
          jfph2: jfph2,
          "jfph.totalpage": totalpage,
          totalydpm: res.data.totalnum,
        })

      }
    })
  },






  //播放start

  //开始播放
  ksbf: function (e) {
    var type = e.currentTarget.dataset.type;
    let that = this
    var musicUrl =""; //音频url
    if (type==0){
      musicUrl = that.data.yp; //音频url
      that.setData({ playStatus: false })
    } else if (type == 1){
      musicUrl = that.data.mymusicUrl; //我的音频url
      that.setData({ myplayStatus: false })
    }else{
      musicUrl = that.data.xturl+e.currentTarget.dataset.yp;
      //将图片改为播放中
      var datas = that.data.works.datas
      var index=e.currentTarget.dataset.index
      for (var i = 0; i < datas.length; i++) {
        if(i==index){
          datas[index].myplayStatus=false
        }else{
          datas[i].myformatedPlayTime="00:00";
          datas[i].myplayStatus=true;
          datas[i].myslider_value="0";
        }
      }
      var works = that.data.works;
      works.datas = datas;
      that.setData({
        works: works,
      })
    }

    innerAudioContext.src = musicUrl;
    innerAudioContext.autoplay = true
    innerAudioContext.onCanplay((res) => {
      var duration = innerAudioContext.duration;
      innerAudioContext.onTimeUpdate((res) => {
        var per = (innerAudioContext.currentTime / innerAudioContext.duration) * 100;
        if (type == 0) {
          that.setData({
            formatedPlayTime: this.formatTime(innerAudioContext.currentTime)
          })
          that.setData({
            slider_value: per//设置slider滑块所在位置
          })
        } else if (type == 1) {
          that.setData({
            myformatedPlayTime: this.formatTime(innerAudioContext.currentTime)
          })
          that.setData({
            myslider_value: per//设置slider滑块所在位置
          })
        }else{
          //播放中
          var index=e.currentTarget.dataset.index
          var datas = that.data.works.datas
          datas[index].myformatedPlayTime=this.formatTime(innerAudioContext.currentTime)
          datas[index].myslider_value=per
          var works = that.data.works;
          works.datas = datas;
          that.setData({
            works: works,
          })
        }
        if (innerAudioContext.duration.toFixed(2) - innerAudioContext.currentTime.toFixed(2) <= 0) {
          that.setStopState(type)
        }
        innerAudioContext.onEnded(() => {
          that.setStopState(type)
        })
      })
    })
    innerAudioContext.play();
  },

  setStopState: function (type) {
    if (type == 0) {
      this.setData({
        formatedPlayTime: '00:00',
        playStatus: true, //图片展示为未播放  
      })
    } else if (type == 1) {
      this.setData({
        myformatedPlayTime: '00:00',
        myplayStatus: true, //图片展示为未播放  
      })
    }else{
      var datas = this.data.works.datas
      for (var i = 0; i < datas.length; i++) {
        datas[i].myformatedPlayTime="00:00";
        datas[i].myplayStatus=true;
        datas[i].myslider_value="0";
      }
      var works = this.data.works;
      works.datas = datas;
      this.setData({
        works: works,
      })
    }
    innerAudioContext.seek(0);
    innerAudioContext.stop();
  },


  //结束播放
  canel_handover(e) {
    innerAudioContext.pause(); //语音暂停
    var type = e.currentTarget.dataset.type;
    if (type == 0) {
      this.setData({
        playStatus: true, //图片展示为未播放  
      })
    } else if (type == 1) {
      this.setData({
        myplayStatus: true, //图片展示为未播放  
      })
    }else{
      //图片展示为未播放
      var index=e.currentTarget.dataset.index
      var datas = this.data.works.datas
      datas[index].myplayStatus=true
      var works = this.data.works;
      works.datas = datas;
      this.setData({
        works: works,
      })
    }
  },


  listenerSlider: function (e) {
    var per = e.detail.value;
    var currentTime = (per / 100) * innerAudioContext.duration;
    innerAudioContext.seek(currentTime);//通过滑块控制音频进度
    this.formatTime(currentTime)
  },


  formatTime: (time) => {
    time = Math.floor(time);
    var m = Math.floor(time / 60).toString();
    m = m.length < 2 ? '0' + m : m;
    var s = (time - parseInt(m) * 60).toString();
    s = s.length < 2 ? '0' + s : s;
    return m + ':' + s;
  },
  //播放end






  removePlay: function () {
    this.setData({
      myformatedPlayTime: '00:00',
      myplayStatus: true, //图片展示为未播放  
      mymusicUrl: '',
      myslider_value: 0,
    })
    innerAudioContext.stop();
    this.setData({
      pstatus: false,
    })
  },




  //开始录音
  ksly: function (e) {
    wx.showLoading({
      title: '录音中....',
    })
    const options = {
      duration: 600000,
      sampleRate: 44100,
      numberOfChannels: 1,
      encodeBitRate: 192000,
      format: 'aac',
      frameSize: 50
    }
    recordmanage.start(options)

    //需要隐藏诗词
    this.setData({
      phidden: true,//是否隐藏诗词
    })
  },



  jsly: function (e) {
    wx.hideLoading()
    var that = this;
    recordmanage.stop(); //先停止录音
    recordmanage.onStop((res) => {  //监听录音停止的事件
      if (res.duration < 1000) {
        wx.showToast({
          title: '录音时间太短'
        })
        return;
      } else {
        var tempFilePath = res.tempFilePath; // 文件临时路径
        that.setData({
          mymusicUrl: tempFilePath
        })
        that.setData({
          myformatedPlayTime: '00:00',
          myplayStatus: true, //图片展示为未播放  
        })
        innerAudioContext.seek(0);
      }
    });
    that.setData({
      pstatus:true,
      phidden: false,//是否隐藏诗词
    })  
  },


  submitPoteryReadLog: function (e) {
    var that = this;
    var mymusicUrl = this.data.mymusicUrl;
    if (mymusicUrl == '') {
      wx.showModal({
        title: '友情提示',
        content: '请上传诗词语音！',
        showCancel: !1,
      })
      return;
    }

    this.setData({
      disabled: true,
      loading: true
    })

    wx.showLoading({
      title: '保存中....',
    })

    wx.uploadFile({
      url: app.myUlife.ulifeUrl + '/upload/uploadReadLog.html', //上传服务器的地址
      filePath: mymusicUrl, //临时路径
      name: 'file',
      header: {
        contentType: "multipart/form-data", //按需求增加
      },
      formData: null,
      success: function (res) {
        var img = JSON.parse(res.data);
        var urls = img.urls;
        that.setData({
          myyp: urls
        })
        that.savePoteryReadLog();
      },
      fail: function (err) {
        wx.hideLoading();
        console.log(err.errMsg);//上传失败
      }
    });
  },


  savePoteryReadLog(){
    var readid = this.data.readid;
    var usid = wx.getStorageSync('usid');
    var username = wx.getStorageSync('name');
    var yp=this.data.myyp;
    wx.request({
      url: app.myUlife.ulifeUrl + 'poetryread/savePoteryReadLog.html',
      data: {
        readid: readid,
        usid: usid,
        username: username,
        yp: yp
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.result) {
          wx.showModal({
            title: '成功',
            content: res.data.msg,
            showCancel: !1,
          });

          wx.switchTab({
            url: '../../task/mytask/mytask',
            success: function (e) {
              var page = getCurrentPages().pop();
              if (page == undefined || page == null) return;
              page.onLoad();
            }
          })
        } else {
          that.setData({
            disabled: false,
            loading: false
          })
          wx.showModal({
            title: '失败',
            content: res.data.msg,
            showCancel: !1,
          });
        }

      }
    })
  },





//..............诗词语音播放start.................
  //开始播放
  ksbfsc: function (e) {
    let that = this
    var index = e.currentTarget.dataset.index;
    var yy = that.data.yy;
    var xturl = that.data.xturl;
    yy[index].playStatus = false;
    that.setData({ yy: yy })
    var musicUrl = xturl+yy[index].YP; //音频url
    innerAudioContext.src = musicUrl;
    innerAudioContext.autoplay = true
    innerAudioContext.play();
    innerAudioContext.onPlay((res) => {
      innerAudioContext.onTimeUpdate((res) => {
        if (innerAudioContext.duration.toFixed(2) - innerAudioContext.currentTime.toFixed(2) <= 0) {
          that.setStopSCState(index)
        }
        innerAudioContext.onEnded(() => {
          that.setStopSCState(index)
        })
      })
    })
  },
  setStopSCState: function (index) {
    let that = this
    var yy = that.data.yy;
    yy[index].playStatus = true;
    that.setData({ yy: yy })
    innerAudioContext.seek(0);
    innerAudioContext.stop();
  },
  //结束播放
  canel_playsc(e) {
    let that = this
    var index = e.currentTarget.dataset.index;
    innerAudioContext.pause(); //语音暂停
    var yy = that.data.yy;
    yy[index].playStatus = true;
    that.setData({ yy: yy })
  },
//..............诗词语音播放end.................


})